package tool

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"strings"

	jwt "github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
)

type Claims struct {
	Exp    int64 `json:"exp"`
	Iat    int64 `json:"iat"`
	Payload string `json:"payload"`
}

type Pl struct{
	Uuid   string `json:"uuid"`
}

func GetJwtToken(secretKey string, iat, seconds int64,uuid string) (string, error) {
	var p = map[string]string{
		"uuid": uuid,
	}

	payload,_ := json.Marshal(p)
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

func GetJwtUuid(tokenString string) (string, error) {
	parts := strings.SplitN(tokenString, " ", 2)
	if !(len(parts) == 2 && parts[0] == "Bearer") {
		return "", errors.New("invalid token")
	}
	
	jwtParts := strings.Split(parts[1], ".")

	if len(jwtParts) != 3 {
		return "", errors.New("invalid token")
	}

	encodedPayload := jwtParts[1]

	dstPayload, _ := base64.RawStdEncoding.DecodeString(encodedPayload)
	logx.Info(string(dstPayload))
	var c Claims
	json.Unmarshal(dstPayload, &c)
	
	logx.Info(c.Payload)
	var p Pl
	dp, _ := base64.URLEncoding.DecodeString(c.Payload)

	json.Unmarshal(dp, &p)

	return p.Uuid, nil
}